package com.hmkj.web.controller.index;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.utils.ValidateUtils;
import com.hmkj.core.constant.PhoneCodeKey;
import com.hmkj.core.constant.PointNid;
import com.hmkj.core.constant.SessionId;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.user.UserModel;
import com.hmkj.core.po.operate.Agent;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.operate.AgentService;
import com.hmkj.core.service.operate.PointRuleService;
import com.hmkj.core.service.user.UserService;
import com.hmkj.web.controller.GenericController;
import com.xiaoleilu.hutool.lang.Validator;
import com.xiaoleilu.hutool.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 注册页面相关controller
 */
@Api(description = "注册页面相关")
@Slf4j
@RestController
@RequestMapping(GenericController.BASE_API_URL + "/userRegister")
public class RegisterController extends GenericController<Integer, User> {

    @Resource
    private UserService userService;
    @Resource
    private AgentService agentService;
    @Resource
    private PointRuleService pointRuleService;

    /**
     * 用户注册提交
     *
     * @return
     */
    @ApiOperation(value = "注册接口", notes = "注册接口")
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public ResultEntity register(
            @ApiParam("手机号") @RequestParam String mobilePhone,
            @ApiParam("密码(rsa加密再base64加密)") @RequestParam String password,
            @ApiParam("手机短信") @RequestParam String phoneCode,
            @ApiParam("邀请码（非必填）") @RequestParam(required = false) String inviteCode) {
        log.info("web用户注册");
        if(!ValidateUtils.isPhone(mobilePhone)){
            throw new BussinessException("手机号格式不正确");
        }
        // 校验短信
        checkUserPhoneCode(mobilePhone, phoneCode, PhoneCodeKey.REGISTER);
        userService.doRegister(new UserModel(u -> {
            u.setMobile(mobilePhone);
            u.setPassword(password);
            u.setSource(getDomain());
            if (StrUtil.isNotBlank(inviteCode)) {
                // 邀请码 找出父级用户id存入新注册的用户
                User parentUser = userService.selectByInviteCode(inviteCode);
                if (null != parentUser) {
                    u.setParentId(parentUser.getId());
                } else {
                    throw new BussinessException("当前邀请码不存在");
                }
            }
        }));
        // 删除短信
        delSession(SessionId.CAPTCHA);
        final User user = userService.selectOne(new User(u -> u.setMobile(mobilePhone)));
        // 注册完成默认登录
        setSession(SessionId.MEMBER_USER, user);
        // 发放积分
        pointRuleService.sendPoint(user.getId(), PointNid.T1);
        return ok(m -> m.put("id", user.getId()));
    }

    /**
     * 发送短信接口
     *
     * @return
     */
    @ApiOperation(value = "发送短信接口", notes = "发送短信接口")
    @ResponseBody
    @RequestMapping(value = "msg", method = RequestMethod.POST)
    public ResultEntity msg(@ApiParam("手机号") @RequestParam String mobilePhone) throws Exception {
        int i = userService.selectCount(new User(u -> {
            u.setMobile(mobilePhone);
            u.setDelFlag(User.DELFLAG.NORMAL.code);
        }));
        if(i>0){
            throw new BussinessException("手机号码已存在");
        }
        log.info("注册发送短信");
        String domain = getDomain();
        Agent agent = agentService.selectAgentByDomain(domain);
        if (agent != null) {
            sendSmsCode(PhoneCodeKey.REGISTER, mobilePhone,agent.getId());
        }else{
            throw new BussinessException("代理商不存在");
        }
        return ok();
    }

    /**
     * 注册短信校验
     *
     * @return
     */
    @ApiOperation(value = "注册短信校验", notes = "注册短信校验")
    @ResponseBody
    @RequestMapping(value = "checkMsg", method = RequestMethod.POST)
    public ResultEntity checkMsg(@ApiParam("手机号") @RequestParam String mobilePhone,
                                 @ApiParam("手机短信") @RequestParam String phoneCode) throws Exception {
        log.info("注册短信校验");
        checkUserPhoneCode(mobilePhone, phoneCode, PhoneCodeKey.REGISTER);
        return ok();
    }

//    @ApiOperation(value = "校验手机号是否可注册", notes = "校验手机号是否可注册<br/> true 未注册, fase 已注册")
//    @ResponseBody
//    @RequestMapping(value = "checkMobilePhone", method = RequestMethod.POST)
//    public ResultEntity checkMobile(@ApiParam("手机号") @RequestParam String mobilePhone,
//                                    @ApiParam("邀请码（非必填）") @RequestParam(required = false) String inviteCode,
//                                    @ApiParam("图片验证码") @RequestParam String code) throws Exception {
//        if (!Validator.isMobile(mobilePhone)) throw new BussinessException("手机号格式不正确");
//        // 校验图片验证码
//        if (!checkCaptcha(code)) throw new BussinessException("图片验证码错误");
//        int i = userService.selectCount(new User(u -> {
//            u.setMobile(mobilePhone);
//            u.setDelFlag(User.DELFLAG.NORMAL.code);
//        }));
//        if (StrUtil.isNotBlank(inviteCode)) {
//            User parentUser = userService.selectByInviteCode(inviteCode);
//            if (null == parentUser) {
//                throw new BussinessException("当前邀请码不存在");
//            }
//        }
//        return ok(i == 0);
//    }

}
